import { SimpleCache } from "@core/cache/simple.cache";
import { ProductModel } from "@models/product.model";
import { ProductRepository } from "@repositories/product.repository";
import { ServiceBase } from "@services/servise.base";

class ProductService extends ServiceBase {
  private static instance: ProductService;
  private repository = new ProductRepository();
  private cache = new SimpleCache<ProductModel>();

  private constructor() {
    super();
  }

  public static getInstance(): ProductService {
    if (!ProductService.instance) {
      ProductService.instance = new ProductService();
    }

    return ProductService.instance;
  }

  protected init(): void {
    async () => {
      await this.loadCache();
    };
  }

  protected concreteDispose(): void {
    this.cache.clear();
  }

  getAll(): ProductModel[] {
    return this.cache.getAll();
  }

  getById(id: string): ProductModel | undefined {
    return this.cache.getById(id);
  }

  getByProductId(productId: string): ProductModel | undefined {
    return this.cache.find((t) => t.productId === productId);
  }

  async remove(record: ProductModel) {
    await this.repository.delete(record);
    this.cache.remove(record);
  }

  async add(record: ProductModel): Promise<ProductModel> {
    const result = await this.repository.add(record);
    this.cache.add(result);

    return result;
  }

  async update(record:ProductModel): Promise<ProductModel>{
    const result = await this.repository.update(record);
    this.cache.update(record);

    return result;
  }

  private async loadCache() {
    this.repository.getAll().then((records) => {
      this.cache.addRange(records);
    });
  }
}

export { ProductService };
